package interceptorfilterdemo;

import interceptorfilterdemo.handlerimpl.HandlerImpl1;
import interceptorfilterdemo.interceptorimpl.InterceptorImpl1;
import interceptorfilterdemo.interceptorimpl.InterceptorImpl2;
import interceptorfilterdemo.interceptorimpl.InterceptorImpl3;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by chenjun on 2017/12/18.
 */
public class HandlerChain {


    private List<Interceptor> interceptors = new ArrayList<>();
    private Iterator<Interceptor> iterator = null;
    private Handler handler = new HandlerImpl1();
    public  HandlerChain(){
        interceptors.add(new InterceptorImpl1());
        interceptors.add(new InterceptorImpl2());
      //  interceptors.add(new InterceptorImpl3()); //有这个拦截器，handler不会执行。
        iterator = interceptors.iterator(); //每次调用iterator都会产生一个新的Iterator对象，通过在这里调用，只会产生一个，这样handler方法的实现才会有效。
    }
    public  void handle(){
        if(iterator.hasNext()) {
            iterator.next().interceptor(this);
        }else{
            handler.handle();
        }
    }
}
